package com.jiuyin.dianjing.api.retrofit;

import com.jiuyin.dianjing.api.constant.ApiConstant;
import com.jiuyin.dianjing.api.interceptor.HttpCacheInterceptor;
import com.jiuyin.dianjing.api.logger.HttpLog;
import com.jiuyin.dianjing.app.HelperApplication;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.jiuyin.dianjing.api.constant.ApiConstant.CACHE_DIR;
import static com.jiuyin.dianjing.api.constant.ApiConstant.CACHE_SIZE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.DEFAULT_TIMEOUT;


/**
 * Description:
 * File: RetrofitServiceManager.java
 * Author: Administrator
 * Create: 2018/07/30 09:37
 *
 * @author Administrator
 */
public class RetrofitServiceManager {
    private Retrofit.Builder mBuilder;
    private HttpCacheInterceptor mHttpCacheInterceptor = new HttpCacheInterceptor();

    private RetrofitServiceManager() {
        mBuilder = getNewBuilder();
    }

    /**
     * 获取RetrofitServiceManager
     *
     * @return RetrofitServiceManager
     */
    public static RetrofitServiceManager getJsonInstance() {
        return SingletonJsonHolder.INSTANCE;
    }

    private Retrofit.Builder getNewBuilder() {
        return new Retrofit.Builder()
                .client(getOkHttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(ApiConstant.getUrl());
    }

    private OkHttpClient getOkHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(getLoggerInterceptor())
                .cache(getCache())
//                .addInterceptor(addTokenInterceptor())
                .addNetworkInterceptor(mHttpCacheInterceptor)
                .retryOnConnectionFailure(true)
                .build();
    }

    /**
     * 缓存设置
     *
     * @return 缓存
     */
    private Cache getCache() {
        File httpCacheDirectory = new File(HelperApplication.getContext().getExternalCacheDir(), CACHE_DIR);
        Cache cache = new Cache(httpCacheDirectory, CACHE_SIZE);
        return cache;
    }

//    private Interceptor addTokenInterceptor() {
//        return chain -> {
//            Request original = chain.request();
//            Request.Builder requestBuilder = original.newBuilder();
//            String timeStamp = String.valueOf(System.currentTimeMillis());
//            String sign = HEADER_APP_TYPE_KEY + "=" + HEADER_APP_TYPE_VALUE + "&" + HEADER_DID_KEY + "=" + HEADER_DID_VALUE + "&"
//                    + HEADER_MODEL_KEY + "=" + HEADER_MODEL_VALUE + "&" + HEADER_TIME_KEY + "=" + timeStamp;
//            String encryptSign = AesUtil.encrypt(sign, "");
//            String token = HelperApplication.getToken();
//            requestBuilder.header(HEADER_APP_TYPE_KEY, HEADER_APP_TYPE_VALUE);
//            requestBuilder.header(HEADER_DID_KEY, HEADER_DID_VALUE);
//            requestBuilder.header(HEADER_TIME_KEY, timeStamp);
//            requestBuilder.header(HEADER_MODEL_KEY, HEADER_MODEL_VALUE);
//            requestBuilder.header(HEADER_SIGN_KEY, encryptSign);
//            requestBuilder.header(HEADER_TOKEN_KEY, token);
//            Request request = requestBuilder.build();
//            return chain.proceed(request);
//        };
//    }

    private Interceptor getLoggerInterceptor() {
        return new HttpLoggingInterceptor(new HttpLog()).setLevel(HttpLoggingInterceptor.Level.BODY);
    }

    /**
     * 获取对应的Service
     *
     * @param service Service 的 class
     * @param <T>     class
     * @return <T>
     */
    public <T> T create(Class<T> service) {
        return mBuilder.build().create(service);
    }

    private static class SingletonJsonHolder {
        private static RetrofitServiceManager INSTANCE =
                new RetrofitServiceManager();
    }
}